package org.jeecg.modules.sxaq.receiver;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.boot.starter.rabbitmq.client.RabbitMqClient;
import org.jeecg.boot.starter.rabbitmq.core.BaseRabbiMqHandler;
import org.jeecg.common.annotation.RabbitComponent;
import org.jeecg.common.base.BaseMap;
import org.jeecg.common.util.DySmsEnum;
import org.jeecg.common.util.DySmsHelper;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.sxaq.anr.entity.RecordAbnormal;
import org.jeecg.modules.sxaq.anr.service.IRecordAbnormalService;
import org.jeecg.modules.sxaq.deviceinfo.entity.DeviceInfo;
import org.jeecg.modules.sxaq.deviceinfo.service.IDeviceInfoService;
import org.jeecg.modules.sxaq.utils.RabbitMQConstant;

import org.jeecg.modules.sxaq.utils.SmsUtils;
import org.jeecg.modules.sxaq.utils.jpush.JiGuangPushService;
import org.jeecg.modules.sxaq.utils.jpush.JpushUtils;
import org.jeecg.modules.sxaq.utils.jpush.PushBean;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserDevice;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserDeviceService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 异常记录处理
 * @Author: DHC
 * @Date: 2020-12-01
 */
@Slf4j
@RabbitComponent(value = "localAnrRecordListener")
public class AnrRecordRabbitMqListener extends BaseRabbiMqHandler<BaseMap> {

    @Autowired
    private IRecordAbnormalService recordAbnormalService;

    @Autowired
    private ISysUserDeviceService sysUserDeviceService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ISysDepartService sysDepartService;

    @Autowired
    private RabbitMqClient rabbitMqClient;


    @Autowired
    private JpushUtils jpushUtils;

    @Autowired
    private SmsUtils smsUtils;

    @Autowired
    private ISysUserService sysUserService;

    @Value("${sxaq.redisUploadTime}")
    private String redisUploadTime;

    @Autowired
    private IDeviceInfoService deviceInfoService;

    @RabbitListener(concurrency = "2-10", bindings = {@QueueBinding(value = @Queue(value = RabbitMQConstant.LOCAL_ANNRECORD_QUEUE + "${sxaq.factoryCode}", durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = RabbitMQConstant.LOCAL_ANNRECORD_EXCHANGE, type = "topic"),
            key = RabbitMQConstant.LOCAL_ANNRECORD_KEY + "${sxaq.factoryCode}")})
    public void onMessage(String message) {

        log.info("-------收到来自云端的异常日志下发--------");

        try {
            JSONObject object = JSONObject.parseObject(message);
            SysUser user = null;
            JSONArray jsonArray = object.getJSONArray("anr");
            List<RecordAbnormal> list = new ArrayList<>();
            if (jsonArray != null && jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject obj = jsonArray.getJSONObject(i);
                    int type = Integer.parseInt(obj.getString("type"));
                    if (type == 7) { // 系统切换
                        continue;
                    }
                    String anrId = obj.getString("anrId");
                    String realname = obj.getString("realname");
                    String sysOrgCode = obj.getString("sysOrgCode");
                    String username = obj.getString("username");
                    String factoryCode = obj.getString("factoryCode");
                    String workNo = obj.getString("workNo");
                    String mobile_single = obj.getString("mobileSingle");
                    DeviceInfo deviceInfo = deviceInfoService.getDeviceBySingle(mobile_single);

                    long eventTime = 0;
                    try {
                        eventTime = Long.parseLong(obj.getString("eventTime"));
                    } catch (Exception e) {
                        eventTime = System.currentTimeMillis();
                    }

                    user = sysUserService.getUserByWorkNo(workNo);

                    if (user == null) {
                        return;
                    }

                    RecordAbnormal recordAbnormal = new RecordAbnormal();
                    recordAbnormal.setType(type);
                    recordAbnormal.setPhone(user.getPhone());
                    recordAbnormal.setRealname(realname);
                    recordAbnormal.setSysOrgCode(sysOrgCode);
                    recordAbnormal.setUsername(username);
                    recordAbnormal.setUserId(user.getId());
                    recordAbnormal.setAnrId(anrId);
                    recordAbnormal.setWorkNo(workNo);
                    recordAbnormal.setEventTime(new java.util.Date(eventTime));
                    recordAbnormal.setMobileModel(deviceInfo.getMobileModel());
                    recordAbnormal.setMobileSystem(deviceInfo.getMobileSystem());
                    recordAbnormal.setMobileVersion(deviceInfo.getMobileVersion());
                    recordAbnormal.setMobileSingle(deviceInfo.getMobileSingle());
                    list.add(recordAbnormal);

                }
            }

            if (list.size() > 0) {
                if (list.size() == 1) {
                    recordAbnormalService.saveOrUpdate(list.get(0));
                } else {
                    recordAbnormalService.saveOrUpdateBatch(list);
                }

                // 查询app_push字段是1的，需要进行推送。
                List<SysUserDevice> pushTokens = sysUserDeviceService.getSysUserDeviceByAppPush();
                if (pushTokens != null && pushTokens.size() > 0) {
                    String push_title = "";
                    if (list.get(0).getType() == 3) {
                        push_title = "网络异常(手机)";
                    } else if (list.get(0).getType() == 4) {
                        push_title = "摄像头异常(手机)";
                    } else if (list.get(0).getType() == 5) {
                        push_title = "检测异常(服务器)";
                    } else if (list.get(0).getType() == 6) {
                        push_title = "上报异常(APP)";
                    } else if (list.get(0).getType() == 7) {
                        push_title = "切换系统(APP)";
                    } else if (list.get(0).getType() == 8) {
                        push_title = "卸载核心文件(APP)";
                    } else if (list.get(0).getType() == 9) {
                        push_title = "卸载程序(APP)";
                    } else if (list.get(0).getType() == 10) {
                        push_title = "删除权限(APP)";
                    }

                    String depart = sysDepartService.queryDepartNameTxtByOrgCode(user.getOrgCode());

                    String push_app = depart + "的" + list.get(0).getRealname() + "[" + list.get(0).getWorkNo() + "]" + "在进入保密区域后，发生" + push_title + "事件。请相关部门及时处理！";
                    jpushUtils.push(push_title, push_app, null);

                    String push_sms = depart + "的" + list.get(0).getRealname() + "[" + list.get(0).getWorkNo() + "]";
                    smsUtils.sendSms(push_sms, push_title);

                }
            }
        } catch (Exception e) {
            log.info("-----收到来自云端的异常日志下发------" + e);
        }
    }
}